package frame;

import com.formdev.flatlaf.FlatLightLaf;
import net.miginfocom.swing.MigLayout;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.File;

public class MainFrame extends JFrame {
	private final JLabel dirLabel = new JLabel("源文件目录");
	private final JTextField dirField = new JTextField(30);
	private final JButton dirButton = new JButton("选择");
	private final JFileChooser fileChooser = new JFileChooser();

	private final JButton translateButton = new JButton("翻译");
	private final JTextPane logPane = new JTextPane();

	private MainFrame() {
		setTitle("批量翻译英文注释");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container contentPane = getContentPane();
		contentPane.setLayout(new MigLayout("wrap 2", "grow"));

		initComponent();
		addListener();

		contentPane.add(dirLabel);
		contentPane.add(dirField, "split 2");
		contentPane.add(dirButton);
		contentPane.add(translateButton, "span 2,center");
		contentPane.add(new JScrollPane(logPane), "span 2, growx, h 400::");

		pack();
		setLocationRelativeTo(null);
	}

	private void initComponent() {
		fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		fileChooser.setFileFilter(new FileFilter() {
			@Override
			public boolean accept(File f) {
				return f.isDirectory() || f.getName().endsWith(".java");
			}

			@Override
			public String getDescription() {
				return "选择目录或者java文件";
			}
		});

		logPane.setContentType("text/html");
		logPane.setEditable(false);
		logPane.setText("<html>");
		JPopupMenu popupMenu = new JPopupMenu();
		JMenuItem menuItem = new JMenuItem("清空日志");
		menuItem.addActionListener(e -> logPane.setText(""));
		popupMenu.add(menuItem);
		logPane.setComponentPopupMenu(popupMenu);

	}

	private void addListener() {
		dirButton.addActionListener(e -> {
			if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
				dirField.setText(fileChooser.getSelectedFile().getAbsolutePath());
			}
		});

		translateButton.addActionListener(e -> {
			translateButton.setEnabled(false);
			File rootFile = new File(dirField.getText());
			if (!rootFile.exists()) {
				JOptionPane.showConfirmDialog(this, "必须是目录或java文件", "提示", JOptionPane.DEFAULT_OPTION);
				return;
			}
			new TranslateWorker(this, rootFile).execute();
		});
	}

	public static void main(String[] args) {
		EventQueue.invokeLater(() -> {
			FlatLightLaf.setup();
			new MainFrame().setVisible(true);
		});
	}

	public JButton getTranslateButton() {
		return translateButton;
	}

	public JTextPane getLogPane() {
		return logPane;
	}
}
